package com.young4j.xinsuiwutuobang.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Json工具类
 * @author 杨飞
 *
 */
public class JsonUtils {
	private static final Logger LOGGER = LoggerFactory.getLogger(JsonUtils.class);
	private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
	/**
	 * 强PORO转为Json
	 * @param obj
	 * @return
	 */
	public static <T> String toJson(T obj){
		String json;
		try {
			json = OBJECT_MAPPER.writeValueAsString(obj);
		} catch (Exception e) {
			LOGGER.error("convert POJO to Json failure",e);
			throw new RuntimeException(e);
		}
		return json;
	}
	/**
	 * 将JSON转换为POJO
	 * @param json
	 * @param type
	 * @return
	 */
	public static <T> T fromJson(String json,Class<T> type){
		T pojo;
		try {
			pojo = OBJECT_MAPPER.readValue(json, type);
		} catch (Exception e) {
			LOGGER.error("convert JSON to POJO failure",e);
			throw new RuntimeException(e);
		}
		return pojo;
	}
}
